# !/usr/bin/python
# coding: utf8

import base64
import hashlib
import hmac
import random


def md5(a_string):
    """
    生成MD5
    :param a_string: 对照
    :return:
    """
    if not isinstance(a_string, (bytes, str)):
        pass
    if isinstance(a_string, str):
        a_string = a_string.encode('utf-8')
    return hashlib.md5(a_string).hexdigest()


def h_mac(key, msg=None, digestmod=None):
    if isinstance(key, str):
        key = key.encode('utf-8')
    if isinstance(msg, str):
        msg = msg.encode('utf-8')
    if isinstance(digestmod, str):
        digestmod = digestmod.encode('utf-8')

    return hmac.new(key, msg, digestmod).hexdigest()


def sha1(a_string):
    if isinstance(a_string, str):
        a_string = a_string.encode('utf-8')
    return hashlib.sha1(a_string).hexdigest()


def sha256(a_string):
    if isinstance(a_string, str):
        a_string = a_string.encode('utf-8')
    return hashlib.sha256(a_string).hexdigest()


def base64encode(value):
    """
    给予Base64对值进行加密
    :param value: 传入值
    :return: 加密结果
    """
    if value:
        if isinstance(value, str):
            value = value.encode('utf-8')
        return base64.b64encode(value).decode('utf-8')
    return None


def base64decode(value):
    """
    给予Base64对值进行解密
    :param value: 传入已加密值
    :return: 解密结果
    """
    if value:
        if isinstance(value, str):
            value = value.encode('utf-8')
        return base64.b64decode(value).decode('utf-8')
    return None


def get_random_str(size=32):
    """
    获取定长随机字符串
    :param size: 结果长度
    :return: 随机字符串
    """
    seed_str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ=_-+<>!@#$%^&*()[]{}|\/?'
    return ''.join(random.choices(seed_str, k=size))
